package com.xw.Utils;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.xw.Exception.HttpRequestFailedException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * HTTP工具类
 * @author YangJianquan
 */
public class HttpUtil {
	
	private final static int CONNECT_TIMEOUT =30;  	//连接超时时间  
	private final static int READ_TIMEOUT=30;  		//设置写的超时时间 
	private final static int WRITE_TIMEOUT=30; 		//设置读取超时时间  
	
	private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);
	private static OkHttpClient client = new OkHttpClient.Builder()  
									            .readTimeout(READ_TIMEOUT,TimeUnit.SECONDS)//设置读取超时时间  
									            .writeTimeout(WRITE_TIMEOUT,TimeUnit.SECONDS)//设置写的超时时间  
									            .connectTimeout(CONNECT_TIMEOUT,TimeUnit.SECONDS)//设置连接超时时间  
									            .build();  
										
	public static final MediaType JSON_Type = MediaType.parse("application/json; charset=utf-8");

    public static String get(String url,Map<String, String> headers) throws HttpRequestFailedException{
        Request.Builder builder = new Request.Builder();
        //添加header
        if (null!=headers){
            for (String key:headers.keySet()){
                String value = headers.get(key);
                builder.addHeader(key,value);
            }
        }
        builder.addHeader("Content-Type","application/json");
        Request request = builder.url(url).get().build();
        return executeRequest(url, request);
    }

    /**
     * put请求
     * @param url
     * @return
     */
    public static String post(String url,Map<String,String> params,Map<String,String> headers) throws HttpRequestFailedException {
        Request.Builder builder = new Request.Builder().url(url);
        //添加header
        if (null!=headers){
            for (String key:headers.keySet()){
                String value = headers.get(key);
                builder.addHeader(key,value);
            }
        }
        //添加请求参数
        if (null==params){
            throw new HttpRequestFailedException("Post请求的参数为空！");
        }
        String json = JSON.toJSONString(params);
        RequestBody body = RequestBody.create(JSON_Type, json);
        builder.post(body);
        Request request = builder.build();
        return executeRequest(url, request);
    }

    /**
     * put请求
     * @param url
     * @return
     */
    public static String post(String url,String jsonParams,Map<String,String> headers) throws HttpRequestFailedException {
        Request.Builder builder = new Request.Builder().url(url);
        //添加header
        if (null!=headers){
            for (String key:headers.keySet()){
                String value = headers.get(key);
                builder.addHeader(key,value);
            }
        }
        //添加请求参数
        if (StringUtils.isEmpty(jsonParams)){
            throw new HttpRequestFailedException("Post请求的参数为空！");
        }
        RequestBody body = RequestBody.create(JSON_Type, jsonParams);
        builder.post(body);
        Request request = builder.build();
        return executeRequest(url, request);
    }

    /**
     * post发送请求，参数为json
     * @param url 请求地址
     * @return
     */
    public static String post(String url){
        Request request = new Request.Builder().url(url).build();
        String ret = "";
        try {
            Response response = client.newCall(request).execute();
            ret = response.body().string();
            logger.info(ret);
        } catch (IOException e) {
            logger.info("请求："+url+"发生异常！原因："+e.getMessage());
        }
        return ret;
    }

    /**
	 * put请求
	 * @param url
	 * @return
	 */
	public static String put(String url,Map<String,String> params,Map<String,String> headers) throws HttpRequestFailedException {
        Request.Builder builder = new Request.Builder().url(url);
        //添加header
        if (null!=headers){
            for (String key:headers.keySet()){
                String value = headers.get(key);
                builder.addHeader(key,value);
            }
        }
        //添加请求参数
		if (null==params){
            throw new HttpRequestFailedException("put请求的参数为空！");
		}
        String json = JSON.toJSONString(params);
        RequestBody body = RequestBody.create(JSON_Type, json);
        builder.put(body);
        Request request = builder.build();
        return executeRequest(url, request);
	}

    /**
     * put请求
     * @param url
     * @return
     */
    public static String put(String url,String jsonParams,Map<String,String> headers) throws HttpRequestFailedException {
        Request.Builder builder = new Request.Builder().url(url);
        //添加header
        if (null!=headers){
            for (String key:headers.keySet()){
                String value = headers.get(key);
                builder.addHeader(key,value);
            }
        }
        //添加请求参数
        if (StringUtils.isEmpty(jsonParams)){
            throw new HttpRequestFailedException("put请求的参数为空！");
        }
        RequestBody body = RequestBody.create(JSON_Type, jsonParams);
        builder.put(body);
        Request request = builder.build();
        return executeRequest(url, request);
    }

    /**
     * delete请求
     * @param url 请求地址
     * @param params 请求参数
     * @param headers 请求头
     * @return
     * @throws HttpRequestFailedException
     */
    public static String delete(String url, Map<String, String> params, Map<String, String> headers) throws HttpRequestFailedException{
        Request.Builder builder = new Request.Builder().url(url);
        //添加header
        if (null!=headers){
            for (String key:headers.keySet()){
                String value = headers.get(key);
                builder.addHeader(key,value);
            }
        }
        //添加请求参数
        if (null!=params ){
            String json = JSON.toJSONString(params);
            RequestBody body = RequestBody.create(JSON_Type, json);
            builder.delete(body);
        }else {
            builder.delete();
        }
        Request request = builder.build();
        return executeRequest(url, request);
    }

    /**
     * delete请求
     * @param url 请求地址
     * @param jsonParams 请求参数
     * @param headers 请求头
     * @return
     * @throws HttpRequestFailedException
     */
    public static String delete(String url, String jsonParams, Map<String, String> headers) throws HttpRequestFailedException{
        Request.Builder builder = new Request.Builder().url(url);
        //添加header
        if (null!=headers){
            for (String key:headers.keySet()){
                String value = headers.get(key);
                builder.addHeader(key,value);
            }
        }
        //添加请求参数
        if (StringUtils.isNotEmpty(jsonParams)){
            RequestBody body = RequestBody.create(JSON_Type, jsonParams);
            builder.delete(body);
        }else {
            builder.delete();
        }
        Request request = builder.build();
        return executeRequest(url, request);
    }
	/**
	 * 执行http请求
	 * @param url url地址
	 * @param request request对象
	 * @return
	 */
	private static String executeRequest(String url, Request request) throws HttpRequestFailedException {
        String result = "";
        Response response = null;
        try {
        	//logger.info("开始请求"+url);
			response = client.newCall(request).execute();
			if (response.isSuccessful()){
                result = response.body().string();
				//logger.info(result);
			}else{
                logger.info("请求："+url+"不成功！错误码："+response.code());
				//请求失败！请求码不在200~300内，即服务器发生异常等。
                throw new HttpRequestFailedException("请求失败，可能是服务器发生错误");
			}
		} catch (IOException e) {
			logger.info("请求："+url+"发生异常！异常原因："+e.getMessage());
            throw new HttpRequestFailedException("请求发生异常，可能是网络发生错误");
		}finally {
			if (null!=response) {
				response.close();
			}
        }
        return result;
	}
}
